<template>
  <div class="app-container">
    <!--客户列表查询条件-->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="客户名称" prop="custName">
          <el-input v-model="queryParams.custName" placeholder="请输入客户名称模糊查询" clearable size="small"
                    @keyup.enter.native="handleQuery" style="width: 200px" @blur="trimOnBlur"/>
        </el-form-item>

        <el-form-item label="客户编号" prop="docNum">
          <el-input
            v-model="queryParams.docNum"
            placeholder="请输入客户编号模糊查询"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
            @blur="trimOnBlur"
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="客户类型" prop="sysDicCustomerType">
          <el-select v-model="queryParams.sysDicCustomerType" filterable
                     placeholder="请选择客户类型" style="width: 200px" clearable size="small">
            <el-option
              v-for="dict in customerTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="custNote">
          <el-input
            v-model="queryParams.custNote"
            placeholder="请输入备注模糊查询"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
            @blur="trimOnBlur"
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:customers:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:customers:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:customers:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['system:customers:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>
    <!--客户展示列表-->
    <el-table v-loading="loading" stripe :data="customersList" @selection-change="handleSelectionChange" :highlight-current-row="true">
      <el-table-column type="selection" width="50" align="center" fixed="left"/>
      <el-table-column type="expand" align="center" width="60">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="备注：">
              <span>{{ props.row.custNote }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="序号" align="center" prop="custNumber" width="80" v-if="columns[0].visible"/>
      <el-table-column label="客户名称" align="center" prop="custName" width="180" v-if="columns[1].visible"/>
      <el-table-column label="客户编号" align="center" prop="docNum" v-if="columns[2].visible" width="180"/>
      <el-table-column label="客户类型" align="center" prop="sysDicCustomerType" v-if="columns[3].visible" width="180">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.crm_dict_customer_type" :value="scope.row.sysDicCustomerType"/>
        </template>
      </el-table-column>
      <el-table-column label="客户地址" align="center" prop="custAddr" v-if="columns[4].visible" :show-overflow-tooltip="true"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:customers:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:customers:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页查询-->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改客户对话框 -->
    <el-dialog v-dialogDrag v-dialogDragWidth :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal=false>
      <el-row :gutter="15">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">

          <el-col :span="12">
            <el-form-item prop="custNumber">
                    <span slot="label">
                      序号
                     <el-tooltip content="序号可留空，建议将常用客户的序号设置的小一些，以便将其排在前面。" placement="top">
                      <i class="el-icon-question"></i>
                      </el-tooltip>
                    </span>
            <el-input v-model="form.custNumber" placeholder="请输入排序序号" clearable :style="{width: '90%'}"
                    @blur="trimOnBlur"/>
           </el-form-item>

           <el-form-item prop="custName">
                    <span slot="label">
                      客户名称
                     <el-tooltip content="客户名称不可重复！" placement="top">
                      <i class="el-icon-question"></i>
                      </el-tooltip>
                    </span>
              <el-input v-model="form.custName" placeholder="请输入客户名称" clearable :style="{width: '90%'}"
                      @blur="trimOnBlur"/>
           </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item prop="docNum">
                    <span slot="label">
                      客户编号
                     <el-tooltip content="客户编号不可重复！" placement="top">
                      <i class="el-icon-question"></i>
                      </el-tooltip>
                    </span>
              <el-input v-model="form.docNum" placeholder="请输入客户编号" clearable :style="{width: '90%'}"
                        @blur="trimOnBlur"/>
            </el-form-item>

            <el-form-item label="客户类型" prop="sysDicCustomerType">
              <el-select v-model="form.sysDicCustomerType" placeholder="请选择客户类型" clearable filterable
                         :style="{width: '100%'}">
                <el-option
                  v-for="dict in dict.type.crm_dict_customer_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="客户地址" prop="custAddr">
              <el-input placeholder="请输入客户地址" type="textarea" maxlength="50" show-word-limit autosize clearable v-model="form.custAddr"
                        :style="{width: '100%'}" @blur="trimOnBlur"></el-input>
            </el-form-item>
            <el-form-item label="备注" prop="custNote">
              <el-input clearable v-model="form.custNote" maxlength="50" show-word-limit autosize clearable type="textarea" placeholder="请输入备注"
                        :style="{width: '100%'}" @blur="trimOnBlur"></el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <confirm ref="component_confirm" @ok="confirm_done"/>
  </div>
</template>

<script>
  import {
    listCustomers,
    getCustomers,
    delCustomers,
    addCustomers,
    updateCustomers,
    listCustomersOrder
  } from "@/api/crm/customers";
  import {newDocNum} from "@/api/oa/docNum";
  import confirm from "../../oa/confirm";
  import {trimOnBlur} from '@/utils/form'

  export default {
    dicts: ['crm_dict_customer_type', 'oa_dict_confirm_status'],
    name: "Customers",
    components: {confirm},
    data() {
      return {
        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 客户表格数据
        customersList: [],
        // 客户类型字典
        customerTypeOptions: [],
        //客户类型字典类型
        crm_dict_customer_type: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          sysDicCustomerType: null,
          crm_dict_customer_type: null,
          docNum: null,
          custName: null,
          custAddr: null,
          custNote: null,
          custNumber: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          custName: [
            {required: true, message: "请输入客户名称", trigger: "change"}
          ],
          docNum: [
            {required: true, message: "请输入客户编号", trigger: "change"}
          ],
          sysDicCustomerType: [
            {required: true, message: "请选择客户类型", trigger: "change"}
          ],
        },
        // 列信息
        columns: [
          {key: 0, label: `序号`, visible: true},
          {key: 1, label: `客户名称`, visible: true},
          {key: 2, label: `客户编号`, visible: true},
          {key: 3, label: `客户类型`, visible: true},
          {key: 4, label: `客户地址`, visible: true},
        ],
      };
    },
    created() {
      this.getList();
    },
    methods: {

      trimOnBlur,

      /** 打开对话框：审核 */
      showDialog_confirm(row) {
        row.tableName = 'crm_customers'
        row.uuidColumn = 'fk_cust_uuid'
        this.$refs.component_confirm.showDialog_confirm(row);

      },

      confirm_done() {
      },

      getList() {
        this.loading = true;
        /** 查询客户列表 */
        listCustomers(this.queryParams).then(response => {
          this.customersList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
        /**获取客户类型数据*/
        this.getDicts("crm_dict_customer_type").then(response => {
          this.customerTypeOptions = response.data;
        });

      },

      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          custUuid: null,
          sysDicCustomerType: null,
          docNum: null,
          custName: null,
          custAddr: null,
          custNote: null,
          custNumber: null
        };
        this.resetForm("form");
      },


      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },


      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },


      /**多选框选中数据*/
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.custUuid)
        this.docNums = selection.map(item => item.docNum)
        this.custNames = selection.map(item => item.custName)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },


      /** 新增按钮操作 */
      handleAdd() {
        this.reset();

        listCustomersOrder().then(response => {
          console.log(response)
          this.list = response.rows
          if(response.rows[0]!=null){
            this.list.forEach(item=>{
              this.form.custNumber=parseFloat(item.custNumber)+1
            })
          }else{
            this.form.custNumber=1
          }
        });

        newDocNum({preCode: 'CUS-', len: 12}).then(response => {
          this.form.docNum = response.msg
        })
        this.open = true;
        this.title = "添加客户";
      },

      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const custUuid = row.custUuid || this.ids
        getCustomers(custUuid).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改客户";
        });
      },


      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.custUuid != null) {
              updateCustomers(this.form).then(response => {
                console.log(response)
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addCustomers(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },


      /** 删除按钮操作 */
      handleDelete(row) {
        const custUuids = row.custUuid || this.ids;
        const custNames = row.custName || this.custNames;
        const docNums = row.docNum || this.docNums;
        this.$confirm('是否确认删除客户名称为"' + custNames + '",客户编号为"' + docNums + '"的客户?', "删除确认", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delCustomers(custUuids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {
        });
      },


      /** 导出按钮操作 */
      handleExport() {
        this.download('/crm/crm/customers/export', {
          ...this.queryParams
        }, `post_${new Date().getTime()}.xlsx`)
      },
    }
  };
</script>
